package io.renren.commons.dynamic.datasource.config;

import java.sql.Connection;
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 多数据源connection上下文
 *
 * @author hou 2019-5-30 11:26:58
 */
public class DynamicConnectionHolder {
    @SuppressWarnings("unchecked")
    private static final ThreadLocal<Deque<Connection>> CONTEXT_HOLDER = new ThreadLocal() {
        @Override
        protected Object initialValue() {
            return new ArrayDeque<>();
        }
    };

    /**
     * 获得当前线程->当前操作->数据源连接
     *
     * @return 数据源连接
     */
    public static Connection peek() {
        return CONTEXT_HOLDER.get().peek();
    }

    /**
     * 设置当前线程->当前操作->数据源连接
     *
     * @param connection 数据源连接
     */
    public static void push(Connection connection) {
        CONTEXT_HOLDER.get().push(connection);
    }

    /**
     * 清空当前线程数据源连接
     */
    public static void poll() {
        Deque<Connection> deque = getConnectionDeque();
        deque.poll();
        if (deque.isEmpty()) {
            CONTEXT_HOLDER.remove();
        }
    }

    public static Deque<Connection> getConnectionDeque() {
        return CONTEXT_HOLDER.get();
    }
}
